<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-plus"
        @click="handleAdd"
      >新增企业</el-button>
    </div>
    <my-table
      :list="list"
      :list-loading="listLoading"
      @modify="handleModify"
      @delete="handleDelete"
    />
    <my-dialog
      :dialog-status="dialogStatus"
      :temp="temp"
      :dialog-form-visible="dialogFormVisible"
      :users="users"
      :click-dialog="clickDialog"
      @add-data="addData"
      @modify-data="modifiedData"
      @close-dialog="closeDialog"
    />
  </div>
</template>

<script>
import {
  addEnterprise,
  queryEnterprise,
  deleteEnterprise,
  searchEnterprise,
  getAllEnterprise,
  modifiedEnterprise,
  getAccountByEnt,
  modifyAccountEnterpriseByEntId
} from '@/api/enterprise'
import { adminGetAccounts } from '@/api/user'
import MyTable from './components/MyTable'
import MyDialog from './components/MyDialog'
import store from '@/store'

export default {
  name: 'EnterpriseItem',
  components: {
    MyTable,
    MyDialog
  },
  data() {
    return {
      list: [],
      listLoading: false,
      users: [],
      clickDialog: false,
      listQuery: {
        page: -1,
        limit: -1,
        account: store.getters.token
      },
      temp: {
        entId: '',
        entName: '',
        province: '安徽省',
        city: '合肥市',
        county: '蜀山区',
        location: '',
        image: '',
        account: ''
      },
      dialogFormVisible: false,
      dialogStatus: ''
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      if (store.getters.role == 0) { // localStorage 会将数字0转换为字符串0，需要使用==
        getAllEnterprise({
          page: -1,
          limit: -1
        })
          .then(response => {
            const enterprise = response.enterprise
            this.list = enterprise.reverse()
            // for (const item of enterprise) {
            //   this.cityOptions.add(item.city)
            // }
            setTimeout(() => {
              this.listLoading = false
            }, 0.5 * 1000)
          })
          .catch(error => {
            console.log(error)
          })
        adminGetAccounts({
          pageNumber: -1,
          limit: -1,
          role: 4,
          account: store.getters.token
        })
          .then(response => {
            const users = response.accountInfo
            this.users = users.map(item => {
              return {
                label: item.userName,
                value: item.account
              }
            })
          })
          .catch(error => {
            console.log(error)
          })
      } else {
        queryEnterprise(this.listQuery)
          .then(response => {
            const enterprise = response.enterprise
            this.list = enterprise.reverse()
            // for (const item of enterprise) {
            //   this.cityOptions.add(item.city)
            // }
            setTimeout(() => {
              this.listLoading = false
            }, 0.5 * 1000)
          })
          .catch(error => {
            console.log(error)
          })
      }
    },
    handleFilter() {
      this.listLoading = true
      if (this.searchList.keys !== '') {
        if (store.getters.role == 0) {
          this.searchList.account = ''
          searchEnterprise(this.searchList)
            .then(response => {
              const enterprise = response.enterprise
              this.list = enterprise.reverse()
              setTimeout(() => {
                this.listLoading = false
              }, 0.5 * 1000)
            }).catch(error => {
              console.log(error)
            })
        } else {
          console.log(333)
          this.searchList.account = store.getters.token
          searchEnterprise(this.searchList)
            .then(response => {
              const enterprise = response.enterprise
              this.list = enterprise.reverse()
              setTimeout(() => {
                this.listLoading = false
              }, 0.5 * 1000)
            }).catch(error => {
              console.log(error)
            })
        }
      } else {
        console.log(111)
        this.fetchData()
      }
    },
    resetTemp() {
      this.temp = {
        entId: '',
        entName: '',
        province: '安徽省',
        city: '合肥市',
        county: '蜀山区',
        location: '',
        image: '',
        account: ''
      }
    },
    handleAdd() {
      this.resetTemp()
      console.log(this.temp)
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
      this.clickDialog = !this.clickDialog
    },
    addData() {
      addEnterprise(this.temp).then(response => {
        this.list.unshift(this.temp)
        this.dialogFormVisible = false
        this.$notify({
          title: '提示',
          message: '添加成功！',
          type: 'success',
          duration: 2000
        })
      })
    },
    async handleModify(row) {
      const account = await this.getAccountByEnt(row.entId)
      this.temp = Object.assign({ account }, row)
      console.log(this.temp)
      this.dialogStatus = 'modify'
      this.dialogFormVisible = true
      this.clickDialog = !this.clickDialog
    },
    async modifiedData() {
      const tempData = Object.assign({}, this.temp)
      const account = tempData.account
      delete tempData.account
      const res_1 = await modifiedEnterprise(tempData)
      const res_2 = await modifyAccountEnterpriseByEntId({
        account,
        entId: tempData.entId
      })
      console.log(res_1, res_2)
      const index = this.list.findIndex(v => v.entId === this.temp.entId)
      this.list.splice(index, 1, this.temp)
      this.dialogFormVisible = false
      this.$notify({
        title: '提示',
        message: '企业信息修改成功！',
        type: 'success',
        duration: 2000
      })
    },
    handleDelete(entId, index) {
      console.log(entId, index)
      deleteEnterprise({ entId })
        .then(response => {
          this.$notify({
            title: '提示',
            message: '删除成功！',
            type: 'success'
          })
          this.list.splice(index, 1)
        })
        .catch(error => {
          console.log(error)
        })
    },
    async getAccountByEnt(entId) {
      return new Promise(async(resolve, reject) => {
        const res = await getAccountByEnt({ entId })
        if (res.accountEnts.length !== 0) {
          resolve(res.accountEnts[0].account)
        } else {
          resolve(null)
        }
      })
    },
    closeDialog() {
      this.dialogFormVisible = false
    }
  }
}
</script>
